package utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.SecretKey;
import io.jsonwebtoken.security.Keys;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JWTUtil {
    private static final Logger logger = LoggerFactory.getLogger(JacksonUtil.class);
    /**
     * 生成密钥
     */
    private static final String SECRET="SDKltwTl3SiWX62dQiSHblEB6O03FG9/vEaivFu6c6g=";
    /**
     * 生成安全密钥
     */
    private static final SecretKey SECRET_KEY=Keys.hmacShaKeyFor(Decoders.BASE64.decode(SECRET));
    /**
     * 设置过期时间
     */
    private static final long EXPIRATION=60*60*1000;

    /**
     * 生成密钥
     * @param claim
     * @return
     */
    public static String genJwt(Map<String,Object> claim){
        //签名算法
        String jwt= Jwts.builder()
                .setClaims(claim)   //自定义内容(载荷)
                .setIssuedAt(new Date())  //设置签发时间
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRATION))   //设置过期时间
                .signWith(SECRET_KEY)    //签名算法
                .compact();
        return jwt;
    }

    /**
     * 解析token
     * @param jwt
     * @return
     */
    public static Claims parerJWT(String jwt){
        if (StringUtils.hasLength(jwt)){
            return null;
        }
        //创建解析器,设置密钥签名
        JwtParserBuilder jwtParserBuilder=Jwts.parserBuilder().setSigningKey(SECRET_KEY);
        Claims claims=null;
        try{
            //解析token
            claims=jwtParserBuilder.build().parseClaimsJws(jwt).getBody();
        }catch (Exception e){
            logger.error("解析令牌错误jwt:{}",jwt,e);
        }
        return claims;
    }

    /**
     * 从token中获取用户id
     * @param jwtToken
     * @return
     */
    public static Integer getUserIdFromToken(String jwtToken){
        Claims claims=JWTUtil.parerJWT(jwtToken);
        if(claims!=null){
            Map<String,Object>userInfo=new HashMap<>(claims);
            return (Integer) userInfo.get("userId");
        }
        return null;
    }
    public static String generateSecret() {
        // 生成随机UUID并移除连字符
        return UUID.randomUUID().toString().replace("-", "");
    }

}
